<template>
  <XtxBread v-if='cateInfo'>
    <XtxBreadItem to="/">首页</XtxBreadItem>
    <Transition name='fade-right' mode='out-in'>
      <!-- 必须加key,因为如果动画中的组件不添加key,那么组件实例会被缓存 -->
      <!-- 添加了key之后，那么组件每次key变化，组件重新渲染 -->
      <XtxBreadItem :key='cateInfo.fcate.id' :to='"/category/" + cateInfo.fcate.id'>{{cateInfo.fcate.name}}</XtxBreadItem>
    </Transition>
    <Transition name='fade-right' mode='out-in'>
      <XtxBreadItem :key='cateInfo.scate.id'>{{cateInfo.scate.name}}</XtxBreadItem>
    </Transition>
  </XtxBread>
</template>
<script>
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { computed } from 'vue'

export default {
  name: 'SubBread',
  setup() {
    // 获取面包屑相关数据
    const store = useStore()
    const route = useRoute()
    // 计算一级和二级分类的数据
    const cateInfo = computed(() => {
      const info = {
        fcate: {},
        scate: {}
      }
      store.state.cate.list.some(first => {
        // 根据路由参数的二级分类的id查找二级分类的详细信息
        // first.children的存在性需要判断（默认只有一级分类）
        const scate = first.children && first.children.find(second => second.id === route.params.id)
        if (scate) {
          // 找到了二级分类，此时应该把一级和二级都得到
          info.fcate.id = first.id
          info.fcate.name = first.name
          info.scate.id = scate.id
          info.scate.name = scate.name
          // 终止继续遍历
          return true
        }
      })
      return info
    })
    return { cateInfo }
  }
}
</script>
